﻿using System.Web.Mvc;
using FrameWork.Util.Extension;

namespace FrameWork.Web.Attribute
{
    public class HandlerAuthorizeAttribute : ActionFilterAttribute
    {
        public bool Ignore { get; set; }
        public HandlerAuthorizeAttribute(bool ignore = true)
        {
            Ignore = ignore;
        }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {

            if (Ignore == false)
            {
                return;
            }
            //var operatorProvider = OperatorProvider.Provider.GetCurrent();
            //if (operatorProvider == null)
            //{
            //    Cookie.SaveWithMinute("huikaoba_login_error", "overdue", 60);
            //    filterContext.Result = new RedirectResult("~/TopManager/Auth/Login");
            //    return;
            //}
            //else if(operatorProvider.TrainingInstitutionId<0)
            //{
            //    Cookie.SaveWithMinute("huikaoba_login_error", "errorTrainingInstitutionId", 60);
            //    filterContext.Result = new RedirectResult("~/TopManager/Auth/Login");
            //    return;
            //}
            if (!this.ActionAuthorize(filterContext))
            {
                filterContext.Result = new ContentResult() { Content = new { state = "error", message = "很抱歉！您的权限不足，访问被拒绝！" }.ToJson() };
                return;
            }
        }
        /// <summary>
        /// action权限验证
        /// </summary>
        /// <param name="filterContext"></param>
        /// <returns></returns>
        private bool ActionAuthorize(ActionExecutingContext filterContext)
        {
            //var operatorProvider = OperatorProvider.Provider.GetCurrent();
            //var roleIds = operatorProvider.RoleIdsStr;

            //var urlHost = HttpContext.Current.Request.Url.Host.ToLower();
            //var urlHostArray = urlHost.Split(new char[] { '.' });
            //if ((urlHostArray.Length > 1) && !RegExp.IsIp(urlHost))
            //{
            //    urlHost = urlHost.Remove(urlHost.LastIndexOf(".", StringComparison.Ordinal));
            //}
            //var keyPrefixPre = urlHost.Replace('.', '_');
            //var cookieHead = $"{keyPrefixPre}_HuiKaoBa_";
            ////获取菜单ID
            //var moduleId = Convert.ToInt32(Cookie.GetValue($"{cookieHead}currentmoduleid"));
            //var action = HttpContext.Current.Request.ServerVariables["SCRIPT_NAME"].ToString();
            
            //return ActionValidate(roleIds, moduleId, action);
            return true;
        }

        /// <summary>
        /// 是否通过权限验证
        /// </summary>
        /// <param name="roleIds"></param>
        /// <param name="moduleId"></param>
        /// <param name="action"></param>
        /// <returns></returns>
        private bool ActionValidate(string roleIds, int moduleId, string action)
        {
            return true;
        }

    }
}